package com.xsq.netty;

import com.xsq.netty.bean.NettyMsg;

import java.nio.charset.Charset;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

public class ClientMsgEncoder extends MessageToByteEncoder<NettyMsg> {

    @Override
    protected void encode(ChannelHandlerContext ctx, NettyMsg msg, ByteBuf out) throws Exception {
        if(null == msg){
            throw new Exception("msg is null");
        }

        String body = msg.getBody();
        byte[] bodyBytes = body.getBytes(Charset.forName("utf-8"));
        out.writeByte(msg.getType());
        out.writeByte(msg.getFlag());
        int length = bodyBytes.length + 6;
        out.writeInt(length);
        out.writeBytes(bodyBytes);
    }

}